package org.geektimes.projects.user.sql;

import cn.hutool.core.util.ObjectUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @FileName: DataSourceManager
 * @Description: 数据源管理器
 * @Author: MaWenHao
 * @Created: 2021/3/1 - 下午11:40
 */
public class DataSourceManager {

    /**
     * 程序主配置文件名称
     */
    private static final String APPLICATION_FILE_NAME = "application.properties";

    /**
     * 数据库连接URL
     */
    private static final String DATABASE_URL = "databaseURL";

    private static final String DATASOURCE_DRIVE = "java.sql.Driver";

    private static String databaseURL;

    /**
     * 初始化DataSourceManager
     */
    static {
        // Properties properties = PropertiesUtil.loadPropertyFile(APPLICATION_FILE_NAME);
        // String url = (String) properties.get(DATABASE_URL);
        // if (StrUtil.isBlank(url)) {
        //     throw new RuntimeException("未配置数据源连接<databaseURL>");
        // }
        // databaseURL = url;
        // String datasourceDriver = (String) properties.get(DATASOURCE_DRIVE);
        // if (StrUtil.isBlank(datasourceDriver)) {
        //     throw new RuntimeException("未配置数据库驱动<java.sql.Driver>");
        // }
        // init(datasourceDriver);
    }

    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(databaseURL);
    }

    private static void init(String datasourceDriver) {
        Connection connection = null;
        try {
            Class.forName(datasourceDriver);
            // connection = DriverManager.getConnection(databaseURL);
            //
            // Statement statement = connection.createStatement();
            // // 删除 users 表
            // System.out.println(statement.execute(DBConnectionManager.DROP_USERS_TABLE_DDL_SQL)); // false
            // // 创建 users 表
            // System.out.println(statement.execute(DBConnectionManager.CREATE_USERS_TABLE_DDL_SQL)); // false
            // System.out.println(statement.executeUpdate(DBConnectionManager.INSERT_USER_DML_SQL));  // 5
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ObjectUtil.isNotEmpty(connection)) {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
